package com.wyd.qxglht.service;

import com.wyd.qxglht.dao.IUsersDao;
import com.wyd.qxglht.dto.UsersDTO;
import com.wyd.qxglht.model.Users;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;



import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
 
@Service
public class UsersServiceImpl implements IUsersService {



    @Resource
    private IUsersDao usersDao;

    @Override
    public Page<Users> findAllPage(UsersDTO dto) {

        Sort sort = Sort.by(Sort.Order.asc("id"));
        Pageable page = PageRequest.of((dto.getPage()-1)*dto.getLimit(), dto.getLimit(),sort);
                return usersDao.findAll(getWhereClause(dto),page);
    }
 

    private Specification<Users> getWhereClause(final UsersDTO dto) {
        return new Specification<Users>(){
            

			@Override
			public Predicate toPredicate(Root<Users> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				
				Predicate predicate = criteriaBuilder.conjunction();
				List<Expression<Boolean>> exList = predicate.getExpressions();
				
				if(dto.getUserName()!=null && !"".equals(dto.getUserName())) {
					exList.add(criteriaBuilder.like(root.<String>get("loginName"), "%"+dto.getUserName()+"%"));
                }
             
                if(dto.getBeginDate()!=null) {
					exList.add(criteriaBuilder.greaterThanOrEqualTo(root.<Date>get("creatTime"), dto.getBeginDate()));
                }
                if(dto.getEndDate()!=null) {
					exList.add(criteriaBuilder.lessThanOrEqualTo(root.<Date>get("creatTime"), dto.getEndDate()));
                }

                

                if(dto.getIsLock()!=null&& !"".equals(dto.getIsLock()) ) {
					exList.add(criteriaBuilder.equal(root.<String>get("isLockout"), dto.getIsLock()));
                }
               


				
				return predicate;
			}
    };
    }


 




    @Override
    public Users saveUsers(Users u) {
     


        return usersDao.save(u);
    }

   

}